package zhr.store.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import zhr.store.common.Result;
import zhr.store.domain.Category;
import zhr.store.service.CategoryService;

import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /**
     * 分页查询分类
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public Result<Page> selectAll(int page, int pageSize) {
        //1.构建分页插件
        Page<Category> pageShow = new Page<>(page, pageSize);
        //2.构建查询条件
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(Category::getSort);
        //3.执行查询
        categoryService.page(pageShow, wrapper);
        return Result.success(pageShow);
    }

    /**
     * 添加分类
     *
     * @param category
     * @return
     */
    @PostMapping
    public Result<String> insertType(@RequestBody Category category) {
        categoryService.save(category);
        return Result.success("添加成功");
    }

    /**
     * 修改分类
     */
    @PutMapping
    public Result<String> update(@RequestBody Category category) {
        categoryService.updateById(category);
        return Result.success("修改成功");
    }

    /**
     * 根据条件查询分类
     */
    @GetMapping("/list")
    public Result<List<Category>> list(Category category) {
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //查询条件
        if (category.getType() != null) {
            categoryLambdaQueryWrapper.eq(Category::getType, category.getType());
        }
        //排序条件
        categoryLambdaQueryWrapper.orderByAsc(Category::getSort)
                .orderByAsc(Category::getUpdateTime);
        //执行查询
        List<Category> list = categoryService.list(categoryLambdaQueryWrapper);
        return Result.success(list);
    }

    /**
     * 删除分类
     */
    @DeleteMapping
    public Result<String> delete(Long ids) {
        categoryService.remove(ids);
        return Result.success("删除成功");
    }

}
